<?php
/**
 * 个人中心
 * Created by PhpStorm.
 * Date: 2018/9/30
 * Time: 下午5:33
 */
namespace Applet\Controller;
use Think\Controller;
header('content-type:text/html;charset=utf-8');
class UserController extends Controller {
    private $userInfo;

    public function __construct()
    {
        $userInfo = decode_token();
        $this->userInfo = empty($userInfo)?"":(object)$userInfo;
    }

    /**
     * @desc user login
     * @author Egor<http://gitee.com/seosite>
     * @param $param
     * @return array
     */
    public function login($param)
    {
        $check = CheckFactoryController::isChildParamSet();
        $check->before('code');

        unset($check);

        $code = $param['code'];//小程序传来的code值

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wxa67687eb23f5818f&secret=67716b6bd9bafec2feade27a64892514&js_code='.$code.'&grant_type=authorization_code';

        //yourAppid为开发者appid.appSecret为开发者的appsecret,都可以从微信公众平台获取；
        $info = file_get_contents($url);//发送HTTPs请求并获取返回的数据，推荐使用curl

        $json = json_decode($info);//对json数据解码
        $arr = get_object_vars($json);
        $openid = $arr['openid'];
        $session_key = $arr['session_key'];


        $model = M('user');

        $userinfo = $model->where(['openid'=>$openid])->find();

        if($userinfo){
            $user_save_data['logins'] = $userinfo['logins'] + 1;
            $user_save_data['last_ip'] = client_ip();
            $user_save_data['last_time'] = time();
            $user_save_data['id'] = $userinfo['id'];
            $reslogin = $model->save($user_save_data);

            if($reslogin){
                $token = _set_token($userinfo,0);
                $userinfo = decode_token($token);
                $userinfo['token']    = $token;
                if($token)  return showErrorMsg($msg = L('_OPERATION_SUCCESS_'),$code = 0,$return_type = 2,$return_data = $userinfo);
                if(!$token) return showErrorMsg($msg = L('_TOKEN_BUILD_ERROR_'),$code = 100004);
            }
            if(!$reslogin) return showErrorMsg($msg = L('_TOKEN_BUILD_ERROR_'),$code = 100002);
        }else{
            $insert_data = [
                'openid'    =>  $openid,
                'session_key'    =>  $session_key,
            ];
            $operation = $model->add($insert_data);
            $userinfo = $model->find($operation);
            $token = _set_token($userinfo,0);
            $userinfo = decode_token($token);
            $userinfo['token']    = $token;

            return showErrorMsg(L('_OPERATION_SUCCESS_'),0,2,$userinfo);
        }
    }


    /**
     * @desc 我发起的
     * @param $param
     * @return array
     */
    public function sponsorList($param)
    {
        $check = CheckFactoryController::isLogin();
        $check->before($param);

        $check = CheckFactoryController::isParamSet();
        $check->before($param);

        unset($check);

		$p = empty($param['p']) ?: $param['p'];
		$listRows = empty($param['listRows']) ? 20 : $param['listRows'];

		$model = M('vote');

        $map['uid'] = $this->userInfo->id;

        list($list,$page) = _listPage($model,$map,$p,'create_time desc','id,title,cover_url,content',$listRows);

        return showList($list,$page);
    }


	/**
	 * @desc 我参与的
	 * @param $param
	 * @return array
	 */
	public function joinList($param)
	{
		$check = CheckFactoryController::isLogin();
		$check->before($param);

		$check = CheckFactoryController::isParamSet();
		$check->before($param);

		unset($check);

		$p = empty($param['p']) ?: $param['p'];
		$listRows = empty($param['listRows']) ? 20 : $param['listRows'];

		$model = M('poll');

		$map['uid'] = $this->userInfo->id;

		list($list,$page) = _listPage($model,$map,$p,'create_time desc','vote_id',$listRows);

		if (!empty($list)){
			foreach ($list as $k=>$v){

				$voteInfo = M('vote')->find($v['vote_id']);
				$list[$k]['id'] = $voteInfo['id'];
				$list[$k]['title'] = $voteInfo['title'];
				$list[$k]['cover_url'] = $voteInfo['cover_url'];
				$list[$k]['content'] = $voteInfo['content'];

			}
		}

		return showList($list,$page);
	}


	/**
	 * @desc wechat
	 * @param $arr
	 * @return string
	 */
    public function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
}